package com.xz.web.controller.common;

import com.xz.common.config.XzConfig;
import com.xz.common.constant.Constants;
import com.xz.common.core.domain.AjaxResult;
import com.xz.common.core.domain.entity.SysUser;
import com.xz.common.core.domain.model.LoginUser;
import com.xz.common.core.redis.RedisCache;
import com.xz.common.utils.StringUtils;
import com.xz.common.utils.file.FileUploadUtils;
import com.xz.common.utils.file.FileUtils;
//import com.xz.customer.service.SendMsgCommonInterfaceService;
import com.xz.framework.config.ServerConfig;
import com.xz.framework.web.service.TokenService;
//import com.xz.personal.vo.PwdVo;
import com.xz.system.service.ISysConfigService;
import com.xz.system.service.ISysUserService;
//import common.ECRandomUtils;
import common.ECUuidGenUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.xz.common.utils.SecurityUtils.getLoginUser;

/**
 * 通用请求处理
 *
 * @author xz
 */
@RestController
public class CommonController {
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private XzConfig xzConfig;

//    @Resource
//    private SendMsgCommonInterfaceService messageService;

    @Resource
    private RedisCache redisCache;

    @Resource
    private ISysConfigService configService;
    @Resource
    private ISysUserService userService;
    @Resource
    private TokenService tokenService;

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete   是否删除
     */
    @GetMapping("common/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        try {
            if (!FileUtils.checkAllowDownload(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = xzConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }
    /**
     * description:根据url下载返回给前端二进制文件流
     *
     * @param request
     * @param response
     * @param url
     */

    @GetMapping("/common/download/url")
    public void downLoadFromUrl(HttpServletRequest request, HttpServletResponse response, String url) {
        try {
            URL urls = new URL(url);
//            根据url创建URL对象
            BufferedInputStream bis = new BufferedInputStream(urls.openStream());
            byte[] tmp = new byte[1024];
            String name = url.substring(url.lastIndexOf('/') + 1);
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.addHeader("Access-Control-Allow-Origin", "*");//后端允许跨域
            response.addHeader("Access-Control-Expose-Headers", "Content-Disposition,download-filename");
//            将文件名转成utf8的字符串形式
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(name.getBytes(), "utf-8"));
//            获取输出流，将文件流返回给前端
            OutputStream out = response.getOutputStream();
            int len = 0;
//            从url指向的链接中读取数据保存到tmp字节数组中，写入到输出流中
            while ((len = bis.read(tmp, 0, 1024)) != -1) {
                out.write(tmp, 0, len);
            }
            bis.close();
            out.close();
        } catch (IOException e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用上传请求
     */
    @PostMapping("/common/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        try {
            // 上传文件路径
            String filePath = xzConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("nginxUrl", xzConfig.getNginxUrl() + fileName);
            ajax.put("url", url);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 管理移动端 文件上传
     */
    @RequestMapping("/api/manage/files")
    @ResponseBody
    public AjaxResult upload(@RequestParam("files") MultipartFile[] files){
        String[] resultFilePath = new String[files.length];
        String url="";//回显路径
        String saveUrl="";//图片提交路径
        int i = 0;
        for (MultipartFile file : files) {
            String fileName = file.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            String newFileName = ECUuidGenUtils.genUUID();
            String paths = newFileName.substring(newFileName.length() - 4);
            String dir = "wechat_img/client/";
            File fileDir = new File(XzConfig.getProfile() + "/" + dir);
            if (!fileDir.exists()) {
                fileDir.mkdirs();
            }
            if (file.isEmpty()) {
                return AjaxResult.error("文件不存在");
            } else {
                try {
                    File dest = new File(XzConfig.getProfile()+ File.separator + dir + File.separator + newFileName + suffix);
                    file.transferTo(dest);
                    resultFilePath[i++] = dir + "/" + newFileName + suffix;
                    System.out.println(XzConfig.getProfile() + File.separator + newFileName + suffix);
                    saveUrl=dir+newFileName+suffix;
                    url= xzConfig.getNginxUrl()+saveUrl;
                } catch (Exception e) {
                    e.printStackTrace();
                    return AjaxResult.error("上传失败");
                }
            }
        }
        String resultUrl="";
        if(resultFilePath.length >0){
            resultUrl= org.apache.commons.lang3.StringUtils.join(resultFilePath,",");
            Map<String,Object> map=new HashMap<>();
            map.put("url",url);
            map.put("saveUrl",saveUrl);
            return AjaxResult.success(map);
        }
        return AjaxResult.error("上传失败");
    }

    /**
     * 本地资源通用下载
     */
    @GetMapping("/common/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        try {
            if (!FileUtils.checkAllowDownload(resource)) {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = xzConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }


//    /*
//     * 发送验证码
//     */
//    @RequestMapping(value = "/common/verifyCode")
//    public AjaxResult verifyPhone(String phone){
//        if(StringUtils.isEmpty(phone)){
//            return AjaxResult.error("手机号不能为空");
//        }
//        // 产生随机数字的验证码
//        String content = ECRandomUtils.getRandomNumberStr(6);
//        try {
//            boolean b = messageService.sendMsgPost(phone, content, null);
//            if(!b){return AjaxResult.error("发送失败");}
//            redisCache.setCacheObject("verify_"+phone.trim(),content, Constant.MSG_CODE_EXPIRE, TimeUnit.SECONDS);
//        } catch (Exception e) {
//            return AjaxResult.error(0,"调用短信接口异常");
//        }
//
//        return AjaxResult.success("发送成功");
//    }
//
//
//
//    /*
//     * 修改密码
//     */
//    @RequestMapping(value = "/common/updatePwd")
//    public AjaxResult updatePwd(@RequestBody @Valid PwdVo pwdVo){
//        if(!pwdVo.getPassword().equals(pwdVo.getRepeatPassword())){
//            return AjaxResult.error("两次输入的密码不一致，请重新输入");
//        }
//        SysUser user = userService.getOne(new QueryWrapper<SysUser>().eq("phonenumber", pwdVo.getPhone()));
//        if(ObjectUtils.isEmpty(user)|| "2".equals(user.getDelFlag())){
//            log.error("用户不存在");
//            return AjaxResult.error("用户不存在");
//        }
//        if("1".equals(user.getStatus())){
//            return AjaxResult.error("用户已被禁用");
//        }
//        String verifyCode = pwdVo.getVerifyCode();
//        String env = configService.selectConfigByKey("MINIPROGRAM_ENV");
//        if("4".equals(env)){
//            Object cacheObject = redisCache.getCacheObject("verify"+pwdVo.getPhone().trim());
//            if(ObjectUtils.isEmpty(cacheObject)){
//                log.error("验证码已过期，请重新发送");
//                return AjaxResult.error("验证码已过期，请重新发送");
//            }
//            if(!verifyCode.equals(cacheObject.toString())){
//                log.error("验证码错误，请重新发送");
//                return AjaxResult.error("验证码错误，请重新发送");
//            }
//        }
//        user.setPassword(SecurityUtils.encryptPassword(pwdVo.getPassword()));
//        user.setUpdateBy(user.getUserName());
//        user.setUpdateTime(new Date());
//        userService.updateById(user);
//        return AjaxResult.success(true);
//    }

    /**
     * 图片上传
     */
    @PostMapping("/updateAvatar")
    public AjaxResult updateAvatar(@RequestParam("file") MultipartFile file) throws IOException {
        if (!file.isEmpty()) {
            LoginUser loginUser = getLoginUser();
            String avatar = FileUploadUtils.upload(xzConfig.getAvatarPath(), file);
            assert loginUser != null;
            SysUser user = userService.getById(loginUser.getUserId());
            user.setAvatar(avatar);
            user.setUpdateTime(new Date());
            userService.updateById(user);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("imgUrl", avatar);
            ajax.put("nginxUrl", xzConfig.getNginxUrl() + avatar);
            return ajax;
        }
        return AjaxResult.error("上传图片异常，请联系管理员");
    }

}
